package handles

import (
	"fmt"
	"strings"
	"sync"
	"time"

	"hawkeye/common/storage"
	"hawkeye/event"
	"hawkeye/protocol"
	"hawkeye/server/model"

	"github.com/panjf2000/gnet/v2"
)

// HeartbeatHandler 心跳事件处理器
type HeartbeatHandler struct {
	BaseHandler
	dataType protocol.HeartbeatData
}

// NewHeartbeatHandler 创建心跳处理器
func NewHeartbeatHandler(connMutex *sync.RWMutex, connections map[gnet.Conn]string) *HeartbeatHandler {
	return &HeartbeatHandler{
		BaseHandler: BaseHandler{
			connMutex:   connMutex,
			connections: connections,
		},
	}
}

// Handle 处理心跳事件
func (h *HeartbeatHandler) Handle(ctx *event.Context, data interface{}) error {
	heartbeatData, err := protocol.Convert(data, h.dataType)
	if err != nil {
		return fmt.Errorf("invalid heartbeat data format: %v", err)
	}

	if heartbeatData.ClientID == "" {
		return fmt.Errorf("invalid heartbeat data: missing client_id")
	}

	connIp := strings.Split(ctx.ConnID, ":")[0]

	storage.GDB.Model(&model.Agent{}).Where("conn_ip = ?", connIp).Updates(map[string]any{"last_heartbeat_dt": time.Now(), "agent_status": 1})

	// 构建报文
	response := protocol.NewHeartbeatMessage(heartbeatData.ClientID)

	// 发送心跳响应
	return h.SendMessage(ctx, response)
}
